using System;
using System.Text.RegularExpressions;

namespace Quiki.ExpressionParsers
{
    public class SimpleLineExpressionParser : IWikiLineExpressionParser
    {
        public SimpleLineExpressionParser(string regexExpression, WikiTextElementType elementType, int level)
        {
            this.elementType = elementType;
            this.level = level;
            regex = new Regex (regexExpression, RegexOptions.Compiled);
        }

        public SimpleLineExpressionParser (string regexExpression, WikiTextElementType elementType)
        {
            this.elementType = elementType;
            regex = new Regex (regexExpression);
        }

        public SimpleLineExpressionParser(
            string regexExpression,
            Func<string, WikiTextElement> elementConstructor)
        {
            this.elementConstructor = elementConstructor;
            regex = new Regex(regexExpression);
        }

        public bool Process (string wikiText, WikiTextElement parentElement)
        {
            Match match = regex.Match (wikiText);
            if (false == match.Success)
                return false;

            WikiTextElement element;

            if (elementConstructor != null)
                element = elementConstructor(wikiText);
            else
                element = new WikiTextElement(elementType, level, match.Groups["text"].Value.Trim());

            parentElement.ChildElements.Add(element);

            return true;
        }

        private readonly Regex regex;
        private readonly Func<string, WikiTextElement> elementConstructor;
        private readonly WikiTextElementType elementType;
        private readonly int? level;
    }
}